<template>
  <span v-if="type == 'text'">
    {{ filterValue }}
  </span>
  <el-select
    v-else
    v-loading="loading"
    :model-value="modelValue"
    :disabled="disabled"
    :placeholder="placeholder"
    :clearable="!noClear"
    :multiple="multi"
    @change="changeValue"
  >
    <el-option v-for="(v, i) in selectList" :key="i" :value="v.value" :label="v.label" />
  </el-select>
</template>
<script>
  import request from '@/utils/request'
  export default {
    name: 'CuSelect',
    props: [
      'disabled',
      'placeholder',
      'modelValue',
      'queryInfo',
      'type',
      'multi',
      'replaceFields',
      'noClear',
      'queryFun'
    ],
    emits: ['update:modelValue', 'change'],
    data() {
      return {
        selectList: [],
        defaultValue: this.modelValue,
        loading: false
      }
    },
    computed: {
      filterValue() {
        const item = this.selectList.find(v => v.code == this.modelValue)
        return item ? item.name : ''
      }
    },
    async created() {
      const query = this.queryInfo && this.queryInfo.url ? this.queryInfo : { url: this.queryInfo }
      this.loading = true
      let arr = this.queryFun ? await this.queryFun() : (await request(query)) || []
      this.loading = false
      arr = arr.data || arr.rows
      if (this.replaceFields) {
        arr = arr.map(v => {
          for (const i in this.replaceFields) {
            v[i] = v[this.replaceFields[i]]
          }
          return v
        })
      }
      this.selectList = arr
    },
    methods: {
      changeValue(value) {
        this.$emit('update:modelValue', value)
        let obj = null
        if (this.multi) {
          obj = this.selectList.filter(v => value.includes(v.value))
        } else {
          obj = this.selectList.find(v => v.value == value)
        }
        this.$emit('change', { value, obj })
      }
    }
  }
</script>
